package cn.elves.model.uua.oauth2.userdetail;


import cn.elves.model.entity.RoleDTO;
import cn.elves.model.entity.dto.UserDTO;
import cn.elves.model.entity.dto.response.ResponseDTO;
import cn.elves.model.provider.AuthProvider;
import cn.elves.model.uua.entity.UserJwt;
import cn.elves.model.uua.mult.MultAuthentication;
import cn.elves.model.uua.mult.MultAuthenticationContext;
import cn.elves.model.uua.mult.authenticator.MultAuthenticator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 集成认证用户服务
 **/
@Service("userDetailsService")
@Slf4j
public class MultUserDetailsService implements UserDetailsService , ApplicationContextAware {



    private Collection<MultAuthenticator> authenticators;

    @Resource
    private AuthProvider authProvider;



    @Override
    public UserJwt loadUserByUsername(String username) throws UsernameNotFoundException {
        MultAuthentication multAuthentication = MultAuthenticationContext.get();
        //判断是否是集成登录
        if (multAuthentication == null) {
            multAuthentication = new MultAuthentication();
        }
        multAuthentication.setUsername(username);
        UserDTO user = this.authenticate(multAuthentication);

        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        System.out.println(encode);
        return new UserJwt(
                user.getName(),
                encode,
                !user.getIsDel(),
                user.getAccountNonExpired(),
                user.getCredentialsNonExpired(),
                user.getAccountNonLocked(),
                this.obtainGrantedAuthorities(user), user.getId().toString());

    }

    /**
     * 获得登录者所有角色的权限集合.
     */
    protected Set<GrantedAuthority> obtainGrantedAuthorities(UserDTO user) {
        try {
            ResponseDTO<Set<RoleDTO>> roleResponse = authProvider.queryRoleByUserId(user.getId().toString());

            if (!roleResponse.isSuccess()) {
                log.error("fail user:{},roles:{}", user.getName(), roleResponse.getMessage());
            }
            Set<RoleDTO> roles = roleResponse.getContent();
            log.info("user:{},roles:{}", user.getName(), roles);

            return roles.stream().map(role -> new SimpleGrantedAuthority(role.getDescription())).collect(Collectors.toSet());
        } catch (Exception e) {
            e.printStackTrace();
            HashSet<GrantedAuthority> grantedAuthorities = new HashSet<>();
            grantedAuthorities.add(new SimpleGrantedAuthority("NONE"));
            return grantedAuthorities;
        }
    }

    private UserDTO authenticate(MultAuthentication multAuthentication) {

        //延迟加载认证器
        if (this.authenticators == null) {
            synchronized (this) {
                Map<String, MultAuthenticator> integrationAuthenticatorMap = applicationContext.getBeansOfType(MultAuthenticator.class);
                if (integrationAuthenticatorMap != null) {
                    this.authenticators = integrationAuthenticatorMap.values();
                }
            }
        }

        if (this.authenticators != null) {
            for (MultAuthenticator authenticator : authenticators) {
                if (authenticator.support(multAuthentication)) {
                    return authenticator.authenticate(multAuthentication);
                }
            }
        }
        return null;
    }

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
